<template>
  <div class="upload-container">
    <input
      @change="fileChanged"
      type="file"
      class="upload-input"
      accept="image/*"
      id="input"
    >
    <div
      class="upload-text"
      v-show="!uploadImg"
      @click="uploadImage"
    >
      <div class="upload-icon">📁</div>
      <span>点击上传图片</span>
    </div>
    <div v-show="uploadImg">
      <el-icon
        class="closeDiv"
        @click="clearImg"
      >
        <CircleClose />
      </el-icon>
      <!-- <div
        class="closeDiv"
        @click="clearImg"
      >×</div> -->
      <el-image
        :src="uploadImg"
        :zoom-rate="1.2"
        :max-scale="7"
        :min-scale="0.2"
        :preview-src-list="[uploadImg]"
        show-progress
        :initial-index="1"
        fit="cover"
      />
    </div>
    <!-- <img
      id="preview"
      class="preview-image"
    > -->
  </div>
</template>

<script setup>
import { defineEmits, ref, defineProps, onMounted } from 'vue';
import { CircleClose } from '@element-plus/icons-vue';

let uploadImg = ref('');
const emit = defineEmits(['fileSelected']);
const props = defineProps({
  src: {
    type: String,
    default: ''
  }
});

onMounted(() => {
  if (props.src) {
    uploadImg.value = props.src;
  }
});

let fileChanged = (event) => {
  if (event.target.files.length) {
    let reader = new FileReader();
    reader.onload = async (e) => {
      uploadImg.value = e.target.result;
      emit('fileSelected', event);
      const input = document.getElementById('input');
      input.value = '';
    };
    reader.readAsDataURL(event.target.files[0]);
  }
  // console.log('1 :>> ', 1);
};

let uploadImage = () => {
  const input = document.getElementById('input');
  input.click();
};

let clearImg = () => {
  uploadImg.value = '';
  emit('fileSelected', undefined);
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
/* 上传组件 */
.upload-container {
  width: 100px;
  height: 100px;
  border: 2px dashed #ccc;
  border-radius: 8px;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.upload-container:hover {
  border-color: #2196f3;
}

.upload-input {
  display: none;
}

.upload-text {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  text-align: center;
  color: #666;
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  position: absolute;
  top: 0;
  left: 0;
}

.upload-icon {
  font-size: 24px;
  margin-bottom: 8px;
  color: #2196f3;
}

/* 显示在右上角 */
.closeDiv {
  position: absolute;
  top: 0;
  right: 0;
  cursor: pointer;
  z-index: 999;
  font-size: 20px;
  color: red;
}
</style>
